<template>
  <view class="app-container">
    <!-- 顶部提示区域 -->
    <view class="header">
      <wd-icon name="scan" class="scan-icon" color="#666666"></wd-icon>
      <text class="header-text">请扫描库位码或筐码</text>
    </view>
    <!-- 中间内容区域 -->

    <view class="content">
      <!-- 已绑定库位 -->
      <view class="section">
        <view class="section-header">
          <text class="section-title">
            <wd-icon name="location"></wd-icon>
            库位
          </text>
        </view>
        <view class="list">
          <view class="list-item">
            <view class="item-main">
              <view class="item-info">
                <wd-input class="item-code" v-model="locationCode" color="#666666"></wd-input>
              </view>
              <view>
                <wd-button :round="false" class="status-icon" @tap="handleBindAll">
                  绑定库位
                </wd-button>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 扫描筐码列表 -->
      <view class="section">
        <view class="section-header">
          <text class="section-title">
            <wd-icon name="list"></wd-icon>
            扫描筐码列表
          </text>
          <text class="section-count">共 {{ basketList.length }} 个</text>
        </view>
        <scroll-view scroll-y style="height: 100%">
          <view class="list" style="max-height: 600rpx">
            <view v-if="basketList.length">
              <wd-swipe-action v-for="(item, index) in basketList" :key="index" class="mt-8">
                <view class="basket-card" :class="{ 'error-basket': item.error }">
                  <view class="basket-header">
                    <view class="basket-title">
                      <view class="basket-code">
                        <wd-icon name="goods" size="36rpx" color="#4080ff"></wd-icon>
                        {{ item.basket }}
                      </view>
                      <view class="storage-status">
                        <wd-icon
                          v-if="item.location && item.location !== locationCode"
                          name="warning"
                          color="#f56c6c"
                        ></wd-icon>
                        <text
                          :class="[
                            'location-text',
                            { 'error-text': item.location !== locationCode },
                          ]"
                        >
                          {{ item.location || '无' }}
                        </text>
                      </view>
                    </view>
                  </view>

                  <view class="basket-content">
                    <view class="info-grid">
                      <view class="info-cell">
                        <view>
                          <wd-icon name="code" size="28rpx" color="#909399"></wd-icon>
                          <text class="info-label">产品编码：</text>
                        </view>
                        <view>
                          <text class="info-value">{{ item.productCode }}</text>
                        </view>
                      </view>
                      <view class="info-cell">
                        <view>
                          <wd-icon name="bags" size="28rpx" color="#909399"></wd-icon>
                          <text class="info-label">产品名称：</text>
                        </view>
                        <view>
                          <text class="info-value">{{ item.productName }}</text>
                        </view>
                      </view>
                      <view class="info-cell">
                        <view>
                          <wd-icon name="discount" size="28rpx" color="#909399"></wd-icon>
                          <text class="info-label">数量：</text>
                        </view>
                        <view>
                          <text class="info-value">{{ item.qty || 0 }}</text>
                        </view>
                      </view>
                      <view class="info-cell" v-if="item.error">
                        <view>
                          <wd-icon name="warning" size="28rpx" color="#f56c6c"></wd-icon>
                          <text class="info-label"></text>
                        </view>
                        <view>
                          <text class="info-value error-info-value">{{ item.error }}</text>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
                <template #right>
                  <view class="swipe-delete" @tap="handleDelScan(index, item.id)">
                    <wd-icon name="delete" color="#f56c6c" size="22px"></wd-icon>
                  </view>
                </template>
              </wd-swipe-action>
            </view>
            <view v-else class="empty">
              <view class="empty-text">暂无扫描数据</view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 底部按钮 -->

    <view class="bottom-button">
      <!-- <scan-code @tap="handleBindLocation" :showButton="true" buttonText="绑定库位" /> -->
      <wd-button
        type="primary"
        block
        :round="false"
        :disabled="!hasUnboundItems || !locationCode"
        @tap="handleConfirm"
      >
        完成绑定
      </wd-button>
    </view>
    <scanCode @scanSuccess="getScanData" />
    <!-- <wd-button @tap="getScanData('W695')">扫筐码</wd-button>

    <wd-button
      @tap="getScanData('S2503210000017;PRO0000078;土豆;15;kg;PUR20250321000000005;深圳海吉星')"
    >
      扫标签码
    </wd-button> -->
  </view>
</template>
<script lang="ts" setup>
import { ref, computed } from 'vue'
import scanCode from '@/components/scanCode/scanCode.vue'
import ScanCodeApi, { ScanPatternType, scanProductInfo } from '@/api/scanCode'

import { useMessage, useToast } from 'wot-design-uni'
import inOrOutStockApi, { ScanInStockSuccessData } from '@/api/inOrOutStock'
import goodsReceiptApi from '@/api/goodsReceipt'
const message = useMessage()
const toast = useToast()

const scrollTop = ref<number>(0)
onPageScroll((e) => {
  scrollTop.value = e.scrollTop
})

// 入库单
const inStockCode = ref('')
const locationCode = ref('')
const basketList = ref<(ScanInStockSuccessData & { error?: string })[]>([])

const hasUnboundItems = computed(() => {
  return basketList.value.length > 0
})
const handleConfirm = () => {
  /// 如果列表有错误信息，则不允许提交
  if (basketList.value.some((item) => item.error)) {
    basketList.value.filter((item) => item.error)[0].error
    toast.error(basketList.value.filter((item) => item.error)[0].error)
    return
  }
  /// 如果列表库码与库位不一致，则提示用户确认是否继续入库
  if (basketList.value.some((item) => item.location !== locationCode.value)) {
    message
      .confirm({
        title: '库位不一致',
        msg: `存在库位不一致的扫描数据，请确认是否已绑定库位？`,
        confirmButtonText: '是',
        cancelButtonText: '否',
      })
      .then(() => {
        uni.navigateBack()
      })
  } else {
    message
      .confirm({
        title: '完成入库',
        msg: `是否完成入库？`,
        confirmButtonText: '是',
        cancelButtonText: '否',
      })
      .then(() => {
        uni.navigateBack()
      })
  }
}

const getScanData = async (basketCode: string) => {
  // 如果扫描的是库位码
  if (ScanPatternType.LOCATION_CODE.test(basketCode)) {
    locationCode.value = basketCode
  } else if (
    ScanPatternType.BASKET_CODE.test(basketCode) ||
    ScanPatternType.BASKET_CODE_TIMESTAMP.test(basketCode)
  ) {
    const productInfo = await getProductByCode(basketCode)
    console.log(productInfo, '产品信息')
    if (basketList.value.find((item) => item.basket === productInfo.basket)) {
      toast.error('该筐已绑定，请重新扫描')
      return
    }
    goodsReceiptApi.getBatchBasketByCode(productInfo.basket).then((res) => {
      console.log(res.data)
      if (res.data.length === 0)
        return basketList.value.push({
          basket: productInfo.basket,
          code: productInfo.basket,
          id: NaN,
          location: productInfo.location,
          parentCode: productInfo.basket,
          productCode: productInfo.productCode,
          productName: productInfo.productName,
          qty: Number(productInfo.qty),
          tranCode: inStockCode.value,
        })

      res.data.forEach((item) => {
        basketList.value.push({
          ...item,
          id: NaN,
          basket: item.parentCode,
          location: item.recInLocation,
          tranCode: inStockCode.value,
        })
      })

      // basketList.value.push({
      //   basket: productInfo.basket,
      //   code: productInfo.basket,
      //   id: NaN,
      //   location: productInfo.location,
      //   parentCode: productInfo.basket,
      //   productCode: productInfo.productCode,
      //   productName: productInfo.productName,
      //   qty: Number(productInfo.qty),
      //   tranCode: inStockCode.value,
      // })
    })

    // 如果扫描的是筐码或标签

    // inOrOutStockApi
    //   .saveOrUpdateTStockTranBasketDetail({
    //     ...productInfo,
    //     location: locationCode.value,
    //     tranCode: inStockCode.value,
    //   })
    //   .then((res) => {
    //     console.log(res, '入库成功')
    //     basketList.value.push(...res.data)
    //     collapseValue.value = '0'
    //   })
  } else {
    toast.error('请扫描正确的标签码或筐码')
  }
}
// 根据筐码获取产品信息
const getProductByCode = async (basketCode: string): Promise<scanProductInfo> => {
  // 先获取建议储位

  if (ScanPatternType.BASKET_CODE_TIMESTAMP.test(basketCode)) {
    const [basket, productCode, productName, qty] = basketCode.split(';')
    const res = await ScanCodeApi.getBasketRecordByCode(basket)

    if (!res?.data?.parentCode) {
      toast.error('该标签未与入库单绑定')
      console.log('该标签未与入库单绑定')
      return
    }
    console.log(res, '筐码信息')
    const productInfo = {
      basket: res.data.parentCode,
      productName: res.data.productName,
      qty: res.data.qty,
      productCode: res.data.productCode,
      tranCode: inStockCode.value,
      location: res.data.recInLocation,
    }
    return productInfo
  }
  try {
    if (ScanPatternType.BASKET_CODE.test(basketCode)) {
      const res: any = await ScanCodeApi.getBasketRecordByCode(basketCode)

      if (!res?.data?.parentCode) {
        console.log('该筐为空，是否去绑定产品信息？')

        message
          .confirm({
            title: '提示',
            msg: '该筐为空，是否去绑定产品信息？',
            confirmButtonText: '是',
            cancelButtonText: '否',
          })
          .then((res) => {
            console.log(res, '用户选择：', res)
            uni.navigateTo({
              url: `/pages/binding/basketBind?basketCode=${basketCode}&inStockCode=${inStockCode.value}`,
            })
          })
        return
      }
      const productInfo = {
        basket: res.data.parentCode,
        productName: res.data.productName,
        qty: res.data.qty,
        productCode: res.data.productCode,
        tranCode: inStockCode.value,
        location: res.data.recInLocation,
      }
      return productInfo
    }
  } catch (error) {
    console.log('扫码解构产品信息失败！', error)
  }
}
// 删除筐码
const handleDelScan = (index: number, id?: number) => {
  message
    .confirm({
      msg: '确定删除吗？',
      title: '警告',
    })
    .then(() => {
      basketList.value.splice(index, 1)
      if (id) {
        inOrOutStockApi.delTStockTranHead(id).then((res) => {
          toast.success('删除成功')
        })
      }
    })

    .catch(() => {
      console.log('点击了取消按钮')
    })
}

// 一键绑定
const handleBindAll = () => {
  if (basketList.value.length === 0) return toast.error('请先扫码')
  if (basketList.value.some((item) => item.location !== locationCode.value)) {
    message
      .confirm({
        title: '警告',
        msg: '当前储位与建议储位不一致，是否继续绑定？',
      })
      .then(() => {
        for (let i = 0; i < basketList.value.length; i++) {
          basketList.value[i].id = NaN
          inOrOutStockApi
            .saveOrUpdateTStockTranBasketDetail({
              ...basketList.value[i],

              location: locationCode.value,
            })
            .then((res) => {
              console.log(res)
              toast.success('绑定成功')
              basketList.value[i].location = locationCode.value
              basketList.value[i].id = res.data[0].id
            })
            .catch((err) => {
              // 将错误信息显示到当前项
              basketList.value[i].error = err?.data.msg || '绑定失败'
              // toast.error('绑定失败')
            })
        }

        // basketList.value.forEach((item, index) => {
        //   item.id = NaN
        //   inOrOutStockApi
        //     .saveOrUpdateTStockTranBasketDetail({
        //       ...item,

        //       location: locationCode.value,
        //     })
        //     .then((res) => {
        //       console.log(res)
        //       toast.success('绑定成功')
        //       basketList.value[index].location = locationCode.value
        //       basketList.value[index].id = res.data[0].id
        //     })
        //     .catch((err) => {
        //       // 将错误信息显示到当前项
        //       basketList.value[index].error = err?.data.msg || '绑定失败'
        //       // toast.error('绑定失败')
        //     })
        // })
      })
      .catch(() => {
        toast.error('取消绑定')
        console.log('点击了取消按钮')
      })
  } else {
    basketList.value.forEach((item, index) => {
      inOrOutStockApi
        .saveOrUpdateTStockTranBasketDetail({
          ...item,
          location: locationCode.value,
        })
        .then(() => {
          toast.success('绑定成功')
        })
        .catch((err) => {
          // 将错误信息显示到当前项

          basketList.value[index].error = err?.data.msg || '绑定失败'
          // toast.error('绑定失败')
        })
    })
  }
}

// 绑定单个
const handleBind = (item: scanProductInfo, index: number) => {
  if (locationCode.value === '') return toast.error('请先扫描库码')
  if (item.location !== locationCode.value)
    message
      .confirm({
        title: '警告',
        msg: '当前储位与建议储位不一致，是否继续绑定？',
      })
      .then(() => {
        inOrOutStockApi
          .saveOrUpdateTStockTranBasketDetail({
            ...item,
            location: locationCode.value,
            tranCode: inStockCode.value,
          })
          .then(() => {
            toast.success('绑定成功')
          })
          .catch((err) => {
            // 将错误信息显示到当前项
            basketList.value[index].error = err?.data.msg || '绑定失败'
            // toast.error('绑定失败')
          })
      })
      .catch(() => {
        toast.error('取消绑定')
        console.log('点击了取消按钮')
      })
}

onLoad((option) => {
  inStockCode.value = option.inStockCode
})
</script>
<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
  height: 100%;

  .header {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20rpx;
    font-size: 34rpx;
    background-color: #ffffff;
    border-bottom: 1px solid #ebeef5;
    .scan-icon {
      margin-right: 32rpx;
      font-size: 50rpx;
    }
    .header-text {
      font-size: 16px;
      color: #303133;
    }
  }
  .content {
    padding: 20rpx;
    overflow: auto;
    .section {
      padding: 20rpx;
      margin-bottom: 20rpx;
      background-color: #f5f7fa;
      border-radius: 8px;
      .section-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-bottom: 20rpx;
        border-bottom: 1px solid #ebeef5;
        .section-title {
          font-size: 15px;
          font-weight: 500;
          color: #303133;
        }
        .section-count {
          font-size: 13px;
          color: #909399;
        }
      }
      .list {
        // .error-card {
        //   border: 1px solid red;
        // }
        padding-top: 10rpx;
        .list-item::marker {
          content: none;
        }
        .list-item {
          padding: 20rpx 0;
          border-bottom: 1px solid #ebeef5;
          &:last-child {
            border-bottom: none;
          }
          .item-main {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 20rpx;
            .item-info {
              display: flex;
              flex-direction: column;
              .item-code {
                margin-bottom: 8rpx;
                font-size: 15px;
                color: #303133;
              }
              .item-time {
                font-size: 12px;
                color: #909399;
              }
            }
          }
        }

        .basket-card {
          .basket-header {
            .basket-title {
              display: flex;
              align-items: center;
              justify-content: space-between;
              .basket-code {
                font-size: 15px;
                font-weight: 500;
                color: #303133;
              }
            }
            .storage-status {
              display: flex;
              align-items: center;

              .location-text {
                margin-left: 10rpx;
                font-size: 28rpx;
                &.error-text {
                  color: #f56c6c;
                }
              }
            }
          }
          .basket-content {
            .info-grid {
              display: flex;
              flex-direction: column;

              .info-cell {
                display: flex;

                align-items: center;
                justify-content: space-between;
                padding: 12rpx 20rpx;

                background: #f8f9fa;

                border-radius: 8rpx;

                .info-label {
                  margin: 0 10rpx 0 20rpx;

                  color: #909399;

                  white-space: nowrap;
                }

                .info-value {
                  overflow: hidden;

                  font-weight: 500;

                  color: #303133;
                  text-overflow: ellipsis;
                }
                .error-info-value {
                  width: 100%;
                  overflow: hidden;
                  font-size: 22rpx;

                  word-break: break-all;
                  //自动换行
                  word-wrap: break-word;
                  //换行
                  white-space: pre-wrap;
                }
                .wd-icon {
                  flex-shrink: 0;
                }
              }
            }

            .error-msg {
              grid-column: span 2;
            }
          }
        }
        .swipe-delete {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 200rpx;
          height: 100%;
          padding: 0 20rpx;
          font-size: 28rpx;
          color: #f56c6c;
        }
        .empty {
          display: flex;
          align-items: center;
          justify-content: center;
          height: 100%;
          padding: 20rpx;
          color: #909399;
        }
      }
    }
  }
  .bottom-button {
    position: fixed;
    right: 0;
    bottom: 0;
    left: 0;
    padding: 20rpx;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    button {
      margin: auto 10rpx;
    }
  }
}
</style>
